import React from 'react'

export type PropagationEventType = 'click'

const eventToPropRecord: Record<PropagationEventType, string> = {
  click: 'onClick',
}

/**
 * @param {PropagationEventType[]} events - 禁止冒泡事件集合
 * @param {ReactElement} element - React 元素
 * @returns {ReactElement} - React.cloneElement 创建的新 React 元素
 */
export function withStopPropagation(
  events: PropagationEventType[],
  element: React.ReactElement,
): React.ReactElement {
  const props: Record<string, any> = { ...element.props }
  for (const key of events) {
    const prop = eventToPropRecord[key]
    props[prop] = function (e: Event) {
      e.stopPropagation()
      element.props[prop]?.(e)
    }
  }
  return React.cloneElement(element, props)
}
